package com.example.micro.es.server.utils;


import com.example.micro.es.server.bean.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Code Farmer
 * @create 2020/10/1 12:16 上午
 */
public class HtmlParseUtil {

    public static void main(String[] args) throws IOException {
        String url = "https://search.jd.com/Search?keyword=java";

        //解析网页 （Jsoup返回的Document 即浏览器Document对象）
        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");

        Elements elements = element.getElementsByTag("li");

        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            System.out.println("======================");
            System.out.println(img);
            System.out.println(price);
            System.out.println(title);

        }

    }


    public List<Content> parseJD(String keywords) throws IOException {
        String url = "https://search.jd.com/Search?keyword=" + keywords;

        //解析网页 （Jsoup返回的Document 即浏览器Document对象）
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");

        List<Content> contents = new ArrayList<>();
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = Content.builder()
                    .img(img)
                    .price(price)
                    .title(title)
                    .build();
            contents.add(content);
        }
        return contents;
    }

}
